package com.yun.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.catalina.connector.Request;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yun.entity.Files;
import com.yun.entity.User;
import com.yun.service.UserService;
import com.yun.service.Impl.UserServiceImpl;

import org.springframework.web.servlet.ModelAndView;

import com.yun.entity.User;
import com.yun.service.UserService;

/**
 * 用户控制器 添加用户和登陆
 * 
 * @author zhangxubin
 *
 */
@Controller
//@RequestMapping(value="/")
public class UserController {
	// 注入service
	@Resource
	private UserService userServiceImpl;
	
	/**
	 * 用户登陆
	 * 
	 * @param phone
	 * @param password
	 * @param model
	 * @return
	 */
	
	@RequestMapping(value = "/tologin")
	@ResponseBody
	public String tologin(@RequestBody User requestUser, HttpSession session) {
		System.out.println(requestUser);

		User user = userServiceImpl.login(requestUser.getPhone(), requestUser.getUserPwd());
		System.out.println("登陆结果：" + user);
		if (user != null) {
			session.setAttribute("existUser", user);
			
			List<Files> files = userServiceImpl.findFilesByUserId(user.getUserId());
			int usedSize = 0;
			
			for (Files file : files) {
				usedSize += file.getFileSize();
			}
			System.out.println("已用内存:"+usedSize);
			session.setAttribute("used_size", usedSize);
			
			return "ok";

		} else {
			return "no";
		}

	}
	@RequestMapping(value = "/index")
	 public String index() {
		 return "admin";
	 }
	/*
	 * public ModelAndView login(@Param("userPwd") String userPwd, String phone,
	 * ModelAndView model,HttpSession session) { System.out.println(userPwd); User
	 * user = userServiceImpl.login(userPwd,phone); if(user!=null) {
	 * //登陆成功将user用户添加到session作用域中 session.setAttribute("User", user); //登陆成功跳转页面
	 * model.setViewName(""); } return model; }
	 */
	@RequestMapping(value="/toRegist")
	@ResponseBody
	public String toRegitst(@RequestBody User requestUser) {
		System.out.println("注册"+requestUser.toString());
		requestUser.setRole("0");
		int result = userServiceImpl.addUser(requestUser);
		System.out.println("注册结果："+result);
		if (result == 0) {
			return "no";
		}
		return "ok";
		
	}
	
	@RequestMapping(value="/isPhoneExist")
	@ResponseBody
	public String isPhoneExist(@RequestBody User requestUser) {
		System.out.println(requestUser);
		User existUser =  userServiceImpl.findUserByPhone(requestUser.getPhone());
		System.out.println("手机号是否存在："+existUser);
		if(existUser==null) {
			return "no";
		}
		return "ok";
				
	}
}
